<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :span="6">
        <div class="mainbox-left">
          <div class="box-card">
            <applicationTypeTag name="应用分类" :handle="true" @getTypeList="getTypeList"
                                @treeClick="treeClick" />
          </div>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="mainbox">
          <div class="filter-container">
            <el-form v-show="showSearch" ref="queryForm" :model="queryParams"
                     :inline="true" label-width="68px" @submit.native.prevent>
              <el-form-item label="应用名称" prop="appName">
                <el-input
                  v-model="queryParams.appName"
                  :maxlength="30"
                  placeholder="请输入应用名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!-- <el-form-item label="应用分类" prop="appType">
                <el-select v-model="queryParams.appType" placeholder="请选择应用分类" clearable size="small">
                  <el-option
                    v-for="dict in dict.type.applicationType"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item> -->
            </el-form>
            <div class="flex-1" />
            <div>
              <div class="flex-1" />
              <div style="display:flex;">
                <!-- <dt-select-person v-model.trim="queryParams.accountReceiver" :is-multiple="true" /> -->
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
              </div>
            </div>
          </div>
          <dt-table
            v-loading="loading"
            :table-opts="tableOpts"
            :row-key="rowKey"
            :pagination-data="{
              total:total,
              queryParams:queryParams
            }"
            @pagination="getList"
          >
            <template #appIcon="scope">
              <appIcon :icon-type="scope.param.iconType" :app-icon="scope.param.appIcon" :active-color="scope.param.iconColor"
                       style="margin:0 auto" />
            </template>
          </dt-table>
        </div>
      </el-col>
      <!-- 添加或修改应用管理对话框 -->
      <dt-dialog :title="title" :visible.sync="open" :is-loading="loading"
                 @comfirmBtn="submitForm" @closeDialog="cancel">
        <div slot="content">
          <el-form ref="form" :model="form" :rules="rules"
                   label-width="130px">
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model.trim="form.appName" placeholder="请输入应用名称" maxlength="20"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item prop="appCode">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" :content="`应用的唯一标识，一经确定后不可修改。`"
                              placement="top-start">
                    <i class="el-icon-question" />
                  </el-tooltip>
                  应用编码
                </span>
              </span>
              <el-input v-model.trim="form.appCode" placeholder="请输入应用编码" :disabled="title=='修改应用'"
                        maxlength="20" show-word-limit class="limit" />
            </el-form-item>
            <el-form-item label="应用来源" prop="appSource">
              <el-radio-group v-model="form.appSource" @change="changeAppSource">
                <el-radio
                  v-for="dict in dict.type.appSource"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否打开新页签" prop="openNewTag">
              <el-radio-group v-model="form.openNewTag" :disabled="form.appSource == 2">
                <el-radio
                  v-for="dict in dict.type.openNewTag"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="是否需要单点集成" prop="isSingleIntegration">
              <el-radio-group v-model="form.isSingleIntegration">
                <el-radio
                  v-for="dict in dict.type.isSingleIntegration"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <!-- <el-form-item prop="isBaseApp">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" :content="`若选择是，则将此应用默认分配给租户；若选择否，则设置租户应用时需手动勾选`" placement="top-start">
                    <i class="el-icon-question" />
                  </el-tooltip>
                  是否基础应用
                </span>
              </span>
              <el-radio-group v-model="form.isBaseApp">
                <el-radio
                  v-for="dict in dict.type.isBaseApp"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item prop="appType">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" :content="`应用分类是为平台门户首页展示做的分类。`"
                              placement="top-start">
                    <i class="el-icon-question" />
                  </el-tooltip>
                  应用分类
                </span>
              </span>
              <el-select v-model="form.appType" placeholder="请选择应用分类" style="width:100%;">
                <el-option
                  v-for="dict in typeList"
                  :key="dict.id"
                  :label="dict.typeName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="form.appSource ==2 " label="应用地址" prop="appAddress"
                          :rules="form.appSource == '2' ? rules.appAddress : [{ required: false }]">
              <el-input v-model.trim="form.appAddress" placeholder="请输入以http://或者https://开头" maxlength="200"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item v-if="title=='修改应用'&&form.appSource===2" label="应用密钥" prop="appSecret">
              <el-input v-model.trim="form.appSecret" placeholder="请输入应用密钥" disabled />
            </el-form-item>
            <!-- <el-form-item prop="appSecret" :rules="form.appSource == '2' ? rules.appSecret :rules.appSecret1 ">
              <span slot="label">
                <span class="span-box">
                  <el-tooltip class="item" effect="dark" :content="`DQBasic平台进行集成时的身份令牌。`" placement="top-start">
                    <i class="el-icon-question" />
                  </el-tooltip>
                  应用密钥
                </span>
              </span>
              <el-row :gutter="0">
                <el-col :span="20">
                  <el-input v-model.trim="form.appSecret" placeholder="请输入应用密钥" :disabled="title=='修改应用'" maxlength="32" show-word-limit class="limit" />
                </el-col>
                <el-col :span="4">
                  <el-button :disabled="title=='修改应用'" type="primary" style="margin-left: 12px;padding: 10px 34px;" @click="generate()">生成</el-button>
                </el-col>
              </el-row>
            </el-form-item> -->
            <el-form-item label="排序" prop="appSort">
              <el-input v-model.trim="form.appSort" placeholder="请输入排序" maxlength="8"
                        show-word-limit class="limit" />
            </el-form-item>
            <el-form-item label="应用图标" prop="appIcon" class="icon_class">
              <uploadIcon ref="uploadIcon" v-model="form.appIcon" :file-type="fileType"
                          :file-size="fileSize" :icon-color.sync="form.iconColor" />
            </el-form-item>
            <el-form-item v-if="title=='修改应用'&&form.appSource===2" label="应用客户端ID" prop="appClientId">
              <el-input v-model.trim="form.appClientId" placeholder="请输入应用客户端ID" disabled />
            </el-form-item>
            <el-form-item v-if="title=='修改应用'&&form.appSource===2" label="平台公钥" prop="platSyPublicKey">
              <el-input v-model.trim="form.sysAppEncry.platSyPublicKey" type="textarea" placeholder="请输入平台公钥"
                        disabled />
            </el-form-item>
            <el-form-item v-if="title=='修改应用'&&form.appSource===2" label="应用私钥" prop="appSecret">
              <el-input v-model.trim="form.sysAppEncry.thirdSyPrivateKey" type="textarea" placeholder="请输入应用私钥"
                        disabled />
            </el-form-item>
            <el-form-item v-if="title=='修改应用'&&form.appSource===2" label="应用盐值" prop="signSalt">
              <el-input v-model.trim="form.signSalt" placeholder="请输入应用盐值" disabled />
            </el-form-item>
            <el-form-item label="描述" prop="remark">
              <el-input v-model.trim="form.remark" :autosize="{minRows: 6, maxRows: 6}" placeholder="请输入描述"
                        maxlength="200" type="textarea" show-word-limit
                        class="limit" />
            </el-form-item>
          <!-- <el-form-item>
            <span>特殊说明：</span>
            <span>秘钥生成后会加密存储到数据库，无法修改和查看，请记录好秘钥。</span>
          </el-form-item> -->
          </el-form>
        </div>
      </dt-dialog>
    </el-row>
    <dtDialog
      title="企业认证选择"
      :visible.sync="visibleState"
      :lock-scroll="false"
      :append-to-body="true"
      :is-loading="companyLoading"
      :width="'1000px'"
      @closeDialog="onModalClosed"
      @comfirmBtn="onSubmit"
    >
      <el-form
        ref="companyForm"
        slot="content"
        label-width="170px"
        :model="companyForm"
        :rules="rules"
        style="position: relative;"
      >
        <el-form-item label="认证信息选择" prop="supplyTypes">
          <el-select v-model.trim="companyForm.supplyTypes" multiple placeholder="请选择认证信息选择"
                     style="width: 100%">
            <el-option
              v-for="dict in dict.type.enterprise_cert"
              :key="dict.label"
              :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
import { listApp, addApp, getApp, updateApp, delApp, updateStatus, addAuthentication, authenticationList } from '@/framework/api/applicationMag/applicationMag'
import Item from '@/framework/layout/components/Sidebar/Item'
import IconPicker from '@/framework/views/system/permission/components/IconPicker'
import { uuId } from '@/framework/utils/uuid'
import { isExternal, checkParameterName, checkAppSecret } from '@/framework/utils/validate'
import applicationTypeTag from './components/applicationType.vue'
import { cloud } from '@/framework/utils/request'
import uploadIcon from './components/uploadIcon.vue'
import appIcon from './components/appIcon.vue'

export default {
  name: 'ApplicationMag',
  components: {
    Item,
    IconPicker,
    applicationTypeTag,
    uploadIcon,
    appIcon
  },
  dicts: ['applicationType', 'appSource', 'isSingleIntegration', 'isBaseApp', 'openNewTag', 'enterprise_cert'],
  data() {
    const validateAppSecret = async (rule, value, callback) => {
      if (value.length > 0 && !checkAppSecret(value)) {
        callback(new Error('请输入字母、数字和下划线'))
      } else callback()
    }
    const validateAppCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入应用编码'))
      } else if (!checkParameterName(value)) {
        callback(new Error('应用编码只能输入字母、数字'))
      } else callback()
    }
    // const validateAppSecret = (rule, value, callback) => {
    //   if (!value) {
    //     callback()
    //   } else if (!checkCode(value)) {
    //     callback(new Error('请输入字母、数字或下划线'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      fileType: [
        'png',
        'jpg',
        'jpeg'
      ],
      fileSize: 0.2,
      typeList: [],
      // 遮罩层
      loading: true,
      // 显隐表格
      isShowTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        appName: null,
        appType: null
      },
      rowKey: 'appId',
      tableOpts: {
        tableData: [],
        firstTableCol: {
          select: false
        },
        tableCol: [
          {
            prop: 'appName',
            label: '应用名称',
            show: true
          },
          {
            prop: 'appCode',
            label: '应用编码',
            show: true
          },
          {
            prop: 'appSource',
            label: '应用来源',
            show: false,
            type: 'dict',
            formatter: (row) => { return this.dict.type.appSource }
          },
          // {
          //   prop: 'isBaseApp',
          //   label: '是否基础应用',
          //   show: true,
          //   width: 120,
          //   type: 'dict',
          //   formatter: (row) => { return this.dict.type.isBaseApp }
          // },
          {
            prop: 'appType',
            label: '应用分类',
            show: true
          },
          {
            prop: 'appIcon',
            label: '图标',
            show: true,
            slotName: 'appIcon',
            showOverflowTooltip: false
            // type: 'image',
            // getImgurl: (row) => {
            //   return process.env.VUE_APP_BASE_API + cloud.file + '/sysFileInfo/private/preview?fileId=' + row.appIcon + '&token=' + this.$store.getters.token
            // }
          // render: (h, { row }) => {
          //   return h('Item', {
          //     attrs: {
          //       icon: row.appIcon
          //     }
          //   })
          // }
          },
          {
            prop: 'appSort',
            label: '排序',
            show: false
          },
          {
            prop: 'remark',
            label: '描述',
            show: false
          },
          {
            prop: 'statusFlag',
            label: '是否启用',
            show: true,
            type: 'switch',
            activeValue: 1,
            inactiveValue: 2,
            switchChange: (row, value) => { return this.statusFlag(row) },
            disabledChange: (row) => { return this.updateDisabled(row) }
          },
          // {
          //   prop: 'isSingleIntegration',
          //   label: '单点集成状态',
          //   show: true,
          //   width: 120,
          //   type: 'dict',
          //   formatter: (row) => { return this.dict.type.isSingleIntegration }
          // },
          // {
          //   prop: 'appSecret',
          //   label: '应用密钥',
          //   show: true
          // },
          {
            prop: 'appAddress',
            label: '应用域名(地址)',
            show: true
          }
        ],
        operator: {
          width: 306,
          fixed: 'right',
          operatorBtn: [
            { text: '修改', permission: ['APPLICATIONMAG_UPDATE_BUTTON'], icon: 'el-icon-edit', click: (row, col, cellValue) => { return this.handleUpdate(row) }, disabledChange: (row) => { return this.updateDisabled(row) } },
            { text: '删除', disabledChange: (row) => { return this.deleteDisabled(row) }, permission: ['APPLICATIONMAG_DEL_BUTTON'], icon: 'el-icon-delete', type: 'danger', click: (row, col, cellValue) => { return this.handleDelete(row) } },
            { text: '企业认证', permission: ['APPLICATIONMAG_AUTHENTICATION_BUTTON'], icon: 'el-icon-set-up', click: (row, col, cellValue) => { return this.authentication(row) }, disabledChange: (row) => { return this.authenticationDisabled(row) } }
          ]
        },
        toolbarBtn: {
          addBtn: {
            label: '新增',
            isShow: true,
            permission: ['APPLICATIONMAG_ADD_BUTTON'],
            type: 'primary',
            disabled: false,
            icon: 'el-icon-plus',
            click: () => {
              this.handleAdd()
            }
          }
        }
      },
      // 表单参数
      form: {
        appIcon: '',
        iconColor: '',
        appSourceDistinguish: 2,
      },
      // 表单校验
      rules: {
        appName: [
          { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        appCode: [
          { required: true, message: '应用编码不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: validateAppCode
          }
        ],
        appIcon: [
          { type: 'array',
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              const temp = this.form.appIcon
              if (Array.isArray(temp) ? temp.length : temp) {
                callback()
              } else {
                callback(new Error('请上传应用图标'))
              }
            } }
        ],
        appSort: [
          { required: true, message: '排序不能为空', trigger: 'blur' },
          { trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!this.validate.checkSort(value)) {
                callback(new Error('排序格式错误'))
              } else callback()
            }
          }
        ],
        appType: [
          { required: true, message: '应用分类不能为空', trigger: 'change' }

        ],
        appAddress: [
          { required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.form.appAddress) {
                callback(new Error('应用地址不能为空'))
              } else if (!isExternal(value)) {
                callback(new Error('应用地址必须以https:// 或者http:// 开头'))
              } else {
                callback()
              }
            }
          }
        ],
        remark: [
          { required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('描述不能为空'))
              } else if (value.length < 35) {
                callback(new Error('输入长度至少为35'))
              } else {
                callback()
              }
            } }
        ],
        appSecret: [
          { required: true, message: '应用密钥不能为空', trigger: 'blur' },
          { required: true, validator: validateAppSecret, trigger: 'blur' }
        ],
        appSecret1: [
          { required: false, validator: validateAppSecret, trigger: 'blur' }
        ],
        appSource: [
          { required: true, message: '应用来源不能为空', trigger: 'blur' }
        ],
        isSingleIntegration: [
          { required: true, message: '是否需要单点集成不能为空', trigger: 'blur' }
        ],
        isBaseApp: [
          { required: true, message: '是否基础应用不能为空', trigger: 'blur' }
        ],
        openNewTag: [{ required: true, message: '是否打开页签不能为空', trigger: 'blur' }],
        supplyTypes: [{ required: true, message: '请选择认证信息选择', trigger: 'change' }]
      },
      visibleState: false,
      companyLoading: false,
      companyForm: {
        supplyTypes: [],
        systemId: ''
      }
    }
  },
  created() {
    this.form = { ...this.form, ...this.initForm() }
    // this.getList()
  },
  methods: {
    // 企业认证
    authentication(row) {
      authenticationList(row.appId).then((res) => {
        this.companyForm.systemId = row.appId
        if (res.data.length > 0) {
          this.companyForm.supplyTypes = res.data
        }
        this.visibleState = true
      })
    },
    authenticationDisabled(row) {},
    onModalClosed() {
      this.companyForm = {
        supplyTypes: [],
        systemId: ''
      }
      this.$refs.companyForm.resetFields()
    },
    onSubmit() {
      this.$refs.companyForm.validate((valid) => {
        if (valid) {
          this.companyLoading = true
          addAuthentication(this.companyForm).then((res) => {
            this.visibleState = false
            this.$dtModal.msgSuccess(res.message)
          }).finally(() => {
            this.companyLoading = false
          })
        }
      })
    },
    // 判断是否修改
    updateDisabled(row) {
      if (row.tenantId == '000000') {
        return false
      } else if (row.isDefault == 1) {
        return false
      } else {
        return true
      }
    },
    // 判断是否删除
    deleteDisabled(row) {
      if (row.tenantId == '000000') {
        if (row.statusFlag == 1) {
          return true
        } else {
          return false
        }
      } else if (row.isDefault == 1) {
        return false
      } else {
        return true
      }
    },
    getTypeList(data) {
      this.typeList = data[0].children.filter((res) => {
        return res
      })
    },
    initForm() {
      return {
        appIcon: '',
        appSource: 1, // 应用来源
        openNewTag: 1, // 是否打开新页签
        isSingleIntegration: 1, // 是否需要单点集成
        isBaseApp: 1 // 是否基础应用
      }
    },
    changeAppSource(data) {
      if (data == 2) {
        this.form.openNewTag = 2
      } else {
        this.form.openNewTag = 1
      }
    },
    treeClick(id) {
      this.queryParams.appType = id
      this.getList()
    },
    /** 查询应用管理列表 */
    getList() {
      this.loading = true
      listApp(this.queryParams).then(({ data: response }) => {
        this.tableOpts.tableData = response.rows
        this.total = response.totalRows
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = { ...{
        appId: null,
        appName: null,
        appCode: null,
        appSource: null,
        isSingleIntegration: null,
        isBaseApp: null,
        appType: '',
        appAddress: '',
        appSecret: null,
        appIcon: '',
        iconColor: '',
        openNewTag: null,
        remark: null,
        appSort: null,
        sysAppEncry: {
          platSyPublicKey: null,
          thirdSyPrivateKey: null
        }
      },
      ...this.initForm() }
      this.$refs?.uploadIcon?.clear()
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.accountReceiver = ''
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.appId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.reset()
      this.form.appSecret = uuId(32)
      this.form.appCode = uuId(8)
      this.form.appType = this.queryParams.appType
      this.open = true
      this.title = '添加应用'
    },
    generate() {
      this.form.appSecret = uuId(32)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const appId = row.appId || this.ids
      getApp(appId).then((response) => {
        const { appIcon, ...res } = response.data
        this.open = true
        const temp = res.iconType == 1 ? (appIcon
          ? [{ fileId: appIcon, url: `${process.env.VUE_APP_BASE_API + cloud.file}/sysFileInfo/private/preview?fileId=${appIcon}&token=${this.$store.getters.token}`, name: '' }]
          : []) : appIcon
        this.form = {
          ...res,
          appIcon: temp
        }
        this.title = '修改应用'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.appSourceDistinguish =2 ;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const { appIcon } = this.form
          const param = {
            appIcon: Array.isArray(appIcon) ? appIcon[0].fileId : appIcon,
            iconType: Array.isArray(appIcon) ? '1' : '2' // 1自定义图片，2图标
          }
          const fn = this.form.appId != null ? updateApp : addApp
          const mes = this.form.appId != null ? '修改' : '新增'
          fn({ ...this.form, ...param }).then((response) => {
            this.$dtModal.msgSuccess(`${mes}成功`)
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appIds = row.appId || this.ids
      this.$dtModal.confirm(`是否确认删除应用名称为"${row.appName}"的数据项？`).then(() => {
        return delApp(appIds)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 是否启用 */
    statusFlag({ appId, statusFlag }) {
      updateStatus(appId, statusFlag).then((res) => {
        this.$dtMessage({
          type: 'success',
          message: '状态修改成功'
        })
        this.getList()
      }).catch(() => {
        this.getList()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.icon_class {
    // color: red;
   .el-col{
      display: flex;
      .el-icon-delete{
        line-height: 36px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
  .tip{
  margin-left: 20px;
}
</style>
<style scoped>
.upload-demo{
    display: flex;
}
.el-upload__tip{
  margin-left: 10px;
}

</style>
